package network;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

public class MultiChatServer extends JFrame implements Runnable{
	ServerSocket server;
	Socket client;
	boolean tFlag;
	MultiChatServerThread mcst;
	StringBuilder data = new StringBuilder();
	
	HashMap<String,MultiChatServerThread> clients =
			new HashMap<>();
	
	public  JTextField message;
	public  JList list;

	private JPanel contentPane;
	private JPanel panel;
	private JPanel panel_1;
	private JButton btnSend;
	private JComboBox comboBox;
	private JScrollPane scrollPane;
	private JTextPane result;
	private JButton btnServerStop;
	private JScrollPane scrollPane_1;
	private JLabel lblNewLabel;
	private JPanel panel_2;
	private JButton btnServerStart;
	private JLabel lblNewLabel_1;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					MultiChatServer frame = new MultiChatServer();
					frame.setVisible(true);
					
					MultiChatClient c = new MultiChatClient();
					c.userID.setText("park");
					c.message.setText("park....");
					c.setLocation(frame.getX(), frame.getY()+frame.getHeight());
					c.setVisible(true);
					
					MultiChatClient c2 = new MultiChatClient();
					c2.userID.setText("kim");
					c2.message.setText("kim.....");
					c2.setLocation(c.getX()+ c.getWidth(), c.getY());
					c2.setVisible(true);
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MultiChatServer() {
		setMinimumSize(new Dimension(400, 270));
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 554, 513);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		contentPane.add(getPanel(), BorderLayout.NORTH);
		contentPane.add(getPanel_1(), BorderLayout.SOUTH);
		contentPane.add(getScrollPane_1(), BorderLayout.CENTER);
		contentPane.add(getScrollPane_1_1(), BorderLayout.WEST);
		try{
			InetAddress ia = InetAddress.getLocalHost();
			String title = "서버IP:" + ia.getHostAddress();
			title += " / Port : 4444";
			setTitle(title);
		}catch(Exception ex){
			
		}
		
		btnServerStop.setEnabled(false);
		btnSend.setEnabled(false);
		
	}

	@Override
	public void run() {
		try{
			server = new ServerSocket(4444);
			tFlag = true;
			dataSet("<div style='border:1px solid #ff0000;background-color:#ffdddd'>"  
			        + "<font color='blue'>서버가 시작되었습니다.</font>");
			SimpleDateFormat sdf = 
				new SimpleDateFormat("서버 시작 시간 : yyyy-MM-dd hh:mm:ss");
			String str = sdf.format(new Date());
			dataSet(str);
			dataSet("</div>");
			
			while(tFlag){
				client = server.accept();
				if(!client.getInetAddress().getHostAddress().equals("127.0.0.1")){
					mcst = new MultiChatServerThread(this, client);
				}
			}
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
		
	}

	public void serverStart(){
		try{
			btnSend.setEnabled(true);
			btnServerStop.setEnabled(true);
			
			btnServerStart.setEnabled(false);
			Thread t = new Thread(this);
			t.start();
		}catch(Exception ex){
			ex.printStackTrace();
		}
		
	}
	public void serverStop(){
		try{
			tFlag = false;
			
			//server.accept()의 blocking mode 해제.
			Socket s = new Socket("127.0.0.1",4444);
			
			//접속된 유저들에게 서버가 중지되었음을 전달하기 위해 
			SocketData d = 
				new SocketData("serverdown", "server", 
						"서버가 종료되었습니다.", null);
			
			if(!clients.isEmpty()) 	mcst.sendMsg(d);
			
			ObjectOutputStream oos = 
				new ObjectOutputStream(s.getOutputStream());
			oos.writeObject(d);
			
			btnSend.setEnabled(false);
			btnServerStop.setEnabled(false);
			btnServerStart.setEnabled(true);

			clients.clear();
			list.setListData(new Vector());
			
			if( server != null) server.close();
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public void sendMsg(){
		SocketData sd = new SocketData("message", "server", message.getText() ,null);
		dataSet(sd);
		mcst.sendMsg(sd);
	}

	
	
	public void dataSet(SocketData sd){
		data.append(sd.getUser() + " : " + sd.getMessage() + "<br/>");
		result.setText(data.toString());
		
		result.setCaretPosition(result.getDocument().getLength());
		
	}
	public void dataSet(String str){
		data.append(str + "<br/>");
		result.setText(data.toString());
		result.setCaretPosition(result.getDocument().getLength());
	}
	
	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setLayout(new BorderLayout(0, 0));
			panel.add(getPanel_2(), BorderLayout.EAST);
		}
		return panel;
	}
	private JPanel getPanel_1() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.setLayout(new BorderLayout(0, 0));
			panel_1.add(getMessage());
			panel_1.add(getBtnSend(), BorderLayout.EAST);
			panel_1.add(getComboBox(), BorderLayout.WEST);
		}
		return panel_1;
	}
	private JTextField getMessage() {
		if (message == null) {
			message = new JTextField();
			message.setText("server message");
			message.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent ev) {
					if(ev.getKeyCode() == KeyEvent.VK_ENTER){
						sendMsg();
					}
				}
			});
			message.setColumns(10);
		}
		return message;
	}
	private JButton getBtnSend() {
		if (btnSend == null) {
			btnSend = new JButton("전송");
			btnSend.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					sendMsg();
				}
			});
		}
		return btnSend;
	}
	private JComboBox getComboBox() {
		if (comboBox == null) {
			comboBox = new JComboBox();
			comboBox.setPreferredSize(new Dimension(60, 21));
			comboBox.addItem(new ImageIcon("imo0.png"));
			comboBox.addItem(new ImageIcon("P:\\workspace\\과정진행\\1403\\1403\\imo1.png"));
			comboBox.addItem(new ImageIcon("P:\\workspace\\과정진행\\1403\\1403\\imo2.png"));
			comboBox.addItem(new ImageIcon("P:\\workspace\\과정진행\\1403\\1403\\imo3.png"));
			comboBox.addItem(new ImageIcon("P:\\workspace\\과정진행\\1403\\1403\\imo4.png"));
			comboBox.addItem(new ImageIcon("P:\\workspace\\과정진행\\1403\\1403\\imo5.png"));
			comboBox.addItem(new ImageIcon("P:\\workspace\\과정진행\\1403\\1403\\imo6.png"));
			comboBox.addItem(new ImageIcon("P:\\workspace\\과정진행\\1403\\1403\\imo7.png"));
			
		}
		return comboBox;
	}
	private JScrollPane getScrollPane_1() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getResult());
			scrollPane.setColumnHeaderView(getLblNewLabel_1());
		}
		return scrollPane;
	}
	private JTextPane getResult() {
		if (result == null) {
			result = new JTextPane();
			result.setContentType("text/html");
		}
		return result;
	}
	private JButton getBtnServerStop() {
		if (btnServerStop == null) {
			btnServerStop = new JButton("서버종료");
			btnServerStop.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					serverStop();
				}
			});
		}
		return btnServerStop;
	}
	private JScrollPane getScrollPane_1_1() {
		if (scrollPane_1 == null) {
			scrollPane_1 = new JScrollPane();
			scrollPane_1.setPreferredSize(new Dimension(130, 2));
			scrollPane_1.setViewportView(getList());
			scrollPane_1.setColumnHeaderView(getLblNewLabel());
		}
		return scrollPane_1;
	}
	private JList getList() {
		if (list == null) {
			list = new JList();
		}
		return list;
	}
	private JLabel getLblNewLabel() {
		if (lblNewLabel == null) {
			lblNewLabel = new JLabel("접속자");
			lblNewLabel.setBorder(new LineBorder(new Color(0, 0, 0)));
			lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
		}
		return lblNewLabel;
	}
	private JPanel getPanel_2() {
		if (panel_2 == null) {
			panel_2 = new JPanel();
			panel_2.add(getBtnServerStart());
			panel_2.add(getBtnServerStop());
		}
		return panel_2;
	}
	private JButton getBtnServerStart() {
		if (btnServerStart == null) {
			btnServerStart = new JButton("서버시작");
			btnServerStart.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					serverStart();
				}
			});
		}
		return btnServerStart;
	}
	private JLabel getLblNewLabel_1() {
		if (lblNewLabel_1 == null) {
			lblNewLabel_1 = new JLabel("메시지");
			lblNewLabel_1.setHorizontalAlignment(SwingConstants.CENTER);
		}
		return lblNewLabel_1;
	}
}
